﻿using HF.HRM.BLL.Service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.DataAnnotations;
using HF.HRM.BLL;
using HF.HRM.MODEL.Models;
using System.Text.Json;

namespace HF.HRM.WEB.Controllers
{

    [Route("api/[controller]")]
    public class LoginController : Controller
    {
        //依赖注入
        private readonly IUserService _userService;

        private readonly ILogger<LoginController> _logger;


        /// <summary>
        /// 构造注入
        /// </summary>
        /// <param name="userService"></param>
        /// <param name="logger"></param>
        public LoginController(IUserService userService, ILogger<LoginController> logger)
        {
            _userService = userService;
            _logger = logger;
        }


        /// <summary>
        /// 获取用户登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost("GetUser")]
        public async Task<IActionResult> GetUser([FromBody] User user)
        {
            if (string.IsNullOrEmpty(user.UserName) || string.IsNullOrEmpty(user.UserPassword))
            {
                _logger.LogWarning("用户密码为空");
                return BadRequest(new { Message = "用户密码为必填项" });
            }
            try
            {
                var isAuthenticated = await _userService.GetAsyncUserInfo(user.UserName, user.UserPassword);
                if (isAuthenticated)
                {
                    _logger.LogInformation($"User {user.UserName} logged in successfully.");
                    return Ok(new { Message = "登录成功" });
                }
                else
                {
                    _logger.LogWarning($"Invalid login attempt for user {user.UserName}.");
                    return Unauthorized(new { Message = "用户的登录尝试无效" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"An error occurred during login. Please try again later {user.UserName}. Stack Trace: {ex.StackTrace}");
                return StatusCode(500, new { Message = "登录期间发生错误。请稍后再试" });
            }
        }
        public IActionResult Index()
        {
            Response.Headers.Add("Access-Control-Allow-Origin", "*");
            Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization");
            return View();
        }
    }
}
